﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Globalization;
using System.Security.Claims;
using Zhao.Common.Helper;
using Zhao.IServer.Field;
using Zhao.IServer.Management_Arena;
using Zhao.Models.AppletDto;
using Zhao.Models.DTO;

namespace Zhao.Arena.MiniProgram.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AppointmentsController : ControllerBase
    {

        private readonly IMapper _mapper;
        private readonly IFieldTypesServer _typeServer;
        private readonly IFieldsServer _fieldsServer;
        private readonly IVenuesServer _venuesServer;
        private readonly IAppointmentsServer _appointmentsServer;

        public AppointmentsController(IMapper mapper, IFieldTypesServer typeServer, IFieldsServer fieldsServer, IVenuesServer venuesServer, IAppointmentsServer appointmentsServer)
        {
            this._mapper = mapper;
            this._typeServer = typeServer;
            this._fieldsServer = fieldsServer;
            this._venuesServer = venuesServer;
            this._appointmentsServer = appointmentsServer;
        }

        /// <summary>
        /// 预约场地
        /// </summary>
        /// <param name="reservation"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<JsonResult> Reservation([FromBody]AppleReservation reservation)
        {

            var result = new ApiResult() { Success = false, Message = "操作失败" };

            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;

            //获取到id
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.Message = "无权限";
                return new JsonResult(result);
            }

            int id = (int)idClaim.ToInt32();

            reservation.userId = id;

            // 基础对象校验
            if (reservation == null)
            {
                result.Message = "预约信息不能为空";
                return new JsonResult(result);
            }

            // 用户信息校验
            if (reservation.userName.IsNullOrWhiteSpace())
            {
                result.Message = "用户姓名不能为空";
                return new JsonResult(result);
            }

            if (!reservation.phone.IsMobileNumber())
            {
                result.Message = "手机号码格式不正确";
                return new JsonResult(result);
            }

            // 日期格式校验
            if (!reservation.displayDate.IsValidIsoDate())
            {
                result.Message = "日期格式应为YYYY-MM-DD";
                return new JsonResult(result);
            }

            // DisplayDate必须>=当前日期
            if (DateTime.TryParseExact(reservation.displayDate, "yyyy-MM-dd",
                CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime displayDate))
            {
                if (displayDate.Date < DateTime.Today)
                {
                    result.Message = "预约日期不能早于当前日期";
                    return new JsonResult(result);
                }
            }

            // 价格校验
            if (reservation.totalPrice <= 0)
            {
                result.Message = "总价格必须大于0";
                return new JsonResult(result);
            }

            if (reservation.infos.Sum(s => s.Price) != reservation.totalPrice)
            {
                result.Message = "价格不一致";
                return new JsonResult(result);
            }

            // 场地信息校验
            if (reservation.infos == null || !reservation.infos.Any())
            {
                result.Message = "至少需要预约一个场地";
                return new JsonResult(result);
            }

            //对场地预约信息进行校验
            foreach (var info in reservation.infos)
            {
                // 场地ID校验
                if (info.fId <= 0)
                {
                    result.Message = "场地ID无效";
                    return new JsonResult(result);
                }

                // 时间有效性校验
                if (info.StartTime >= info.EndTime)
                {
                    result.Message = "开始时间必须早于结束时间";
                    return new JsonResult(result);
                }
            }


            //如果验证都通过了传递给服务层 进行数据层面的查询
            //如果没问题就传递给服务层

            result = await _appointmentsServer.AppleBookingAVenue(reservation);

            return new JsonResult(result);
        }

        /// <summary>
        /// 获取用户的预约订单信息
        /// </summary>
        /// <param name="status">订单状态：-1-全部，0-待支付，3-已预约，5-已完成，7-已取消</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns></returns>
        [HttpGet]
        [Route("user-orders/{pageIndex:int}/{pageSize:int}")]
        [Route("user-orders/{pageIndex:int}/{pageSize:int}/{status:int}")]
        //[Authorize]
        public async Task<JsonResult> GetUserAppointmentOrders(short? status = -1, int pageIndex = 1, int pageSize = 10)
        {
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;

            if (idClaim.IsNullOrWhiteSpace())
            {
                return new JsonResult(new PageModel<AppointmentOrderDto>
                {
                    code = -1,
                    msg = "无权限",
                    data = new List<AppointmentOrderDto>()
                });
            }

            int userId = (int)idClaim.ToInt32();
            var result = await _appointmentsServer.GetUserAppointmentOrders(userId, status, pageIndex, pageSize);
            //var result = await _appointmentsServer.GetUserAppointmentOrders(1004, status, pageIndex, pageSize);

            return new JsonResult(result);
        }

        /// <summary>
        /// 取消预约订单
        /// </summary>
        /// <param name="cancelRequest">取消预约请求</param>
        /// <returns>操作结果</returns>
        [HttpPost("cancel")]
        [Authorize]
        public async Task<JsonResult> CancelAppointments([FromBody] CancelAppointmentsRequest cancelRequest)
        {
            var result = new ApiResult { Success = false, Message = "取消订单失败" };

            // 1. 获取当前用户ID
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.Message = "无权限，请登录";
                return new JsonResult(result);
            }
            int userId = (int)idClaim.ToInt32();

            // 2. 验证请求参数
            if (cancelRequest == null || cancelRequest.OrderId <= 0)
            {
                result.Message = "请提供有效的订单ID";
                return new JsonResult(result);
            }

            // 3. 调用服务层方法处理取消预约
            result = await _appointmentsServer.CancelUserAppointments(userId, cancelRequest.OrderId);

            return new JsonResult(result);
        }


    }
}
